<template>
	<div class="role">
		<el-form class="search_form" :model="payload" label-width="90px">
			<el-row>
				<el-col :span="6">
					<el-form-item label="角色名称" prop="roleName">
						<el-input v-model="payload.roleName" placeholder="请输入角色名称" />
						<el-input v-show="false" />
					</el-form-item>
				</el-col>
				<el-col :span="18" class="search_buttons">
					<el-button type="primary" @click="queryRoleList">搜索</el-button>
					<el-button @click="resetPayload">重置</el-button>
				</el-col>
			</el-row>
		</el-form>

		<ContentTable
			v-bind="tableConfig"
			v-model:page="page"
			:data="tableData"
			:total="total"
			:page-change="queryRoleList"
		>
			<template #toolbar>
				<el-button type="primary" @click="handleAddClick">新 建</el-button>
			</template>
			<template #handler="{ row }">
				<template v-if="row.id != 1">
					<el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
				</template>
			</template>
		</ContentTable>

		<el-dialog v-model="open" :title="dialogTitle" width="650" top="10vh" :before-close="handleCancel">
			<el-form ref="formRef" :model="formData" :rules="rules" label-width="90px">
				<el-form-item label="角色名称" prop="roleName">
					<el-input v-model="formData.roleName" placeholder="请输入角色名称" />
				</el-form-item>
				<el-form-item label="显示排序" prop="roleSort">
					<el-input-number v-model="formData.roleSort" :min="0" />
				</el-form-item>
				<el-form-item label="权限" prop="routerList">
					<div class="tree_box">
						<el-tree
							ref="deptRef"
							:data="menusTree"
							:props="{ label: 'label', children: 'children' }"
							show-checkbox
							node-key="id"
							style="width: 100%"
							default-expand-all
							empty-text="加载中，请稍候"
						/>
					</div>
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input v-model="formData.remark" type="textarea" rows="3" maxlength="500" show-word-limit />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button type="primary" @click="handleSubmit">确 定</el-button>
				<el-button @click="handleCancel">取 消</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import { selectRoles, insertRole, updateRole, selectRoleRoutes, deleteRole } from '@/service/system/role'
import ContentTable from '@/components/ContentTable'
import { tableConfig, rules } from './config'
import { selectMenus } from '@/service/system/menu'
import { ElMessage, ElMessageBox } from 'element-plus'

const payload = ref<any>({})
const tableData = ref([])
const total = ref(0)
const page = ref({ pageNum: 1, pageSize: 10 })
async function queryRoleList() {
	const res = await selectRoles({ ...payload.value, ...page.value })
	tableData.value = res.list
	total.value = res.total
}
queryRoleList()
function resetPayload() {
	payload.value = {}
	page.value.pageNum = 1
	queryRoleList()
}

const formData = ref<any>({ roleSort: 0 })
const menusTree = ref<any>([])
const open = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const deptRef = ref()
async function handleEdit(row: any) {
	for (const key of ['id', 'roleName', 'roleSort', 'remark']) {
		formData.value[key] = row[key]
	}
	const menus = await selectMenus(null)
	menusTree.value = tableTree(menus, 0)
	const routes = await selectRoleRoutes({ id: row.id })
	if (routes?.length) {
		nextTick(() => {
			routes.forEach((v: number) => {
				nextTick(() => {
					deptRef.value.setChecked(v, true, false)
				})
			})
		})
	}
	dialogTitle.value = '编辑'
	open.value = true
}
function handleDelete(row: any) {
	ElMessageBox.confirm('确认删除此数据？', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(async () => {
			await deleteRole(row.id)
			ElMessage.success('删除成功！')
			queryRoleList()
		})
		.catch(() => {})
}
async function handleAddClick() {
	const menus = await selectMenus(null)
	menusTree.value = tableTree(menus, 0)
	dialogTitle.value = '新建'
	open.value = true
}
function handleCancel() {
	open.value = false
	formData.value = { roleSort: 0 }
	formRef.value.resetFields()
}
function handleSubmit() {
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			const ids = getDeptAllCheckedKeys()
			formData.value['routerList'] = ids
			if (formData.value.id) {
				await updateRole(formData.value)
				ElMessage.success('编辑成功')
				handleCancel()
				queryRoleList()
			} else {
				await insertRole(formData.value)
				ElMessage.success('创建成功')
				handleCancel()
				queryRoleList()
			}
		}
	})
}

/** 所有部门节点数据 */
function getDeptAllCheckedKeys() {
	// 目前被选中的部门节点
	let checkedKeys = deptRef.value.getCheckedKeys()
	// 半选中的部门节点
	let halfCheckedKeys = deptRef.value.getHalfCheckedKeys()
	checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
	return checkedKeys
}
function tableTree(menus: any, pid: number): any[] {
	const list: any = []
	menus?.forEach((menu: any) => {
		if (menu.parentId === pid) {
			const children = tableTree(menus, menu.id)
			if (children.length) {
				menu.children = children
			}
			const obj = {
				id: menu.id,
				value: menu.id,
				label: menu.menuName,
				children: menu.children
			}
			if (!menu.children) delete menu.children
			list.push(obj)
		}
	})
	return list
}
</script>

<style lang="less" scoped>
.tree_box {
	width: 100%;
	height: 300px;
	border: 1px solid rgba(0, 0, 0, 0.2);
	border-radius: 5px;
	padding: 10px;
	overflow-y: scroll;
}
</style>
